'''
Created on 16 Apr 2012

@author: karulis
'''

import crypt
from PySide import QtGui
from BaseTab import BaseTab

class AddTab(BaseTab):
    '''
    classdocs
    '''


    def __init__(self, parent = None):
        '''
        Constructor
        '''
        super(AddTab, self).__init__(parent)

        userLabel = QtGui.QLabel("Name:")
        self.userEdit = QtGui.QLineEdit()

        passwordLabel = QtGui.QLabel("Password:")
        self.passwordEdit = QtGui.QLineEdit()
        self.passwordEdit.setEchoMode(QtGui.QLineEdit.Password)

        rePasswordLabel = QtGui.QLabel("Retype password:")
        self.rePasswordEdit = QtGui.QLineEdit()
        self.rePasswordEdit.setEchoMode(QtGui.QLineEdit.Password)

        addButton = QtGui.QPushButton("Add user")
        addButton.clicked.connect(self.add_clicked)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(userLabel)
        mainLayout.addWidget(self.userEdit)
        mainLayout.addWidget(passwordLabel)
        mainLayout.addWidget(self.passwordEdit)
        mainLayout.addWidget(rePasswordLabel)
        mainLayout.addWidget(self.rePasswordEdit)
        mainLayout.addWidget(addButton)
        mainLayout.addStretch(1)
        self.setLayout(mainLayout)

    def refresh_gui(self):
        self.userEdit.setText("")
        self.passwordEdit.setText("")
        self.rePasswordEdit.setText("")

    def add_clicked(self):
        if not len(self.userEdit.text()):
            self.show_message("User name is empty")
            return
        if not len(self.passwordEdit.text()):
            self.show_message("Password is empty")
            return
        if not self.passwordEdit.text() == self.rePasswordEdit.text():
            self.show_message("Passwords do not match")
            return
        self.add_user(self.userEdit.text(), self.passwordEdit.text())

    def add_user(self, user, password):
        cryptedPass = crypt.crypt(password, "aa")
        ret = self.execute("useradd %s -p '%s'" % (user, cryptedPass))
        if "" != ret:
            self.show_message(ret)
        else:
            self.refresh.emit()
